package com.ztman.service.tenant.service.impl;

import cn.hutool.core.convert.Convert;
import com.ztman.basic.base.service.SuperCacheServiceImpl;
import com.ztman.basic.cache.model.CacheKeyBuilder;
import com.ztman.basic.database.mybatis.conditions.Wraps;
import com.ztman.basic.utils.BeanPlusUtil;
import com.ztman.service.common.cache.tenant.TenantCacheKeyBuilder;
import com.ztman.service.tenant.dao.DatasourceConfigMapper;
import com.ztman.service.tenant.dto.DatasourceConfigSaveDTO;
import com.ztman.service.tenant.entity.DatasourceConfig;
import com.ztman.service.tenant.service.DatasourceconfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.ztman.basic.utils.BizAssert.isFalse;

/**
 * <p>
 * 业务实现类
 * 企业
 * </p>
 *
 * @author wsd
 * @date 2019-10-24
 */
@Slf4j
@Service("DatasourceConfigService2Impl")
@RequiredArgsConstructor
public class DatasourceConfigServiceImpl extends SuperCacheServiceImpl<DatasourceConfigMapper, DatasourceConfig> implements DatasourceconfigService {
    @Autowired
    private DatasourceConfigMapper datasourceConfigMapper;
    @Override
    protected CacheKeyBuilder cacheKeyBuilder() {
        return new TenantCacheKeyBuilder();
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public DatasourceConfig save(DatasourceConfigSaveDTO data) {

        // 1， 保存租户 (默认库)
        DatasourceConfig config = BeanPlusUtil.toBean(data, DatasourceConfig.class);
        // defaults 库
        datasourceConfigMapper.save(config);
        return config;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(List<Long> ids) {
        List<String> tenantCodeList = listObjs(Wraps.<DatasourceConfig>lbQ().select(DatasourceConfig::getName).in(DatasourceConfig::getId, ids), Convert::toStr);
        if (tenantCodeList.isEmpty()) {
            return true;
        }
        return removeByIds(ids);
    }
}
